package com.smart.manager.wiki.entities.repository;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.lang.Opt;
import com.smart.common.entities.constant.ArcoTips;
import com.smart.common.entities.core.Page;
import com.smart.manager.wiki.entities.body.RDocAgreement;
import com.smart.manager.wiki.entities.models.WikiDocAgreement;
import com.smart.manager.wiki.entities.models.query.QWikiDocAgreement;
import io.ebean.DB;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * @author Administrator
 */
@Service
@Log4j2
@RequiredArgsConstructor
public class DocAgreementRepository {


    public Page<WikiDocAgreement> pageList(RDocAgreement.SearchBody search) {

        QWikiDocAgreement query = new QWikiDocAgreement();
        Opt.ofBlankAble(search.getCode()).ifPresent(x -> query.code.contains(x));
        Opt.ofBlankAble(search.getTitle()).ifPresent(x -> query.title.contains(x));
        query.order().id.desc();
        query.setFirstRow(search.firstRow()).setMaxRows(search.maxRows());
        return new Page<WikiDocAgreement>().load(query.findPagedList());
    }

    public void add(RDocAgreement.EditBody body) {
        WikiDocAgreement record = readOne(body.getCode(), false, false);
        Assert.isNull(record, "创建失败:, 协议代码已存在");
        BeanUtil.copyProperties(body, WikiDocAgreement.class).setReadCount(0).save();
    }


    public void update(Long id, RDocAgreement.EditBody body) {
        QWikiDocAgreement query = new QWikiDocAgreement();
        WikiDocAgreement record = query.id.eq(id).setMaxRows(1).findOne();
        Assert.notNull(record, "修改失败:协议数据不存在或已被删除");
        BeanUtil.copyProperties(body, record);
        Objects.requireNonNull(record).update();
    }

    public int delByIds(List<Long> ids) {
        List<WikiDocAgreement> list = new QWikiDocAgreement().id.in(ids).findList();
        Assert.notEmpty(list, ArcoTips.DELETE_NOT_FOUND);
        return DB.deleteAll(list);
    }


    /**
     * @param code      协议代码
     * @param checkNull 是否检查空值
     * @param addCount  是否增加阅读次数
     * @return {@code WikiDocAgreement}
     */
    public WikiDocAgreement readOne(String code, Boolean checkNull, boolean addCount) {
        WikiDocAgreement agreement = new QWikiDocAgreement().code.eq(code).setMaxRows(1).findOne();
        if (checkNull) {
            Assert.notNull(agreement);
        }
        if (addCount) {
            agreement.setReadCount(agreement.getReadCount() + 1);
            agreement.update();
        }
        return agreement;

    }


}
